/**
 * @Description: 用户信息全局状态
 * @Author: jiangang
 * @Date: 2022-04-01
 * @LastEditTime: 11:21:50
 */
import http from '@/http';
import routes from '@/router/routes'
import router from '@/router';
import Vue from 'vue'

const state = {
  baseInfo: {
    createTime: '',
    isDeleted: '',
    menuCodeList: ['login', 'home'],
    realName: '',
    roleIdList: null,
    salt: '',
    status: 1,
    userId: '',
    userType: '',
    username: ''
  }
}
function updateRoute(list, parent) {
  if (!list?.length) {
    return
  }
  const currentRoutes = router.getRoutes().map(item => {
    return item.name
  })
  list.filter(route => {
    return state.baseInfo.menuCodeList.includes(route.name)
  }).forEach(item => {
    const page = {
      path: item.path,
      name: item.name,
      meta: {
        title: item.title,
        isFull: item.isFull,
        onlyMenu: !!item.onlyMenu,
        requireAuth: item.requireAuth !== false,
        keepAlive: !!item.keepAlive,
      }
    }
    if (item.component) {
      page.component = item.component
    } else {
      page.component = resolve => require([`@/view${item.componentPath}`], resolve)
    }
    if (page.path && !currentRoutes.includes(page.name)) {
      if (parent?.name) {
        router.addRoute(parent.name, page)
      } else {
        router.addRoute(page)
      }
    }
    if (item.children && item.children.length) {
      updateRoute(item.children, item)
    }
  })
}

const actions = {
  // updateUserInfo({ commit, state }) {
  updateUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      http.get('/sys/user/info').then(res => {
        // TODO
        // res.menuCodeList.push(...['operation_deviceList', 'operation_quotaList', 'share', 'share_content', 'setting_message_white_list', 'operation_device_admin', 'network_firewall_admin'])
        res.menuCodeList.push(...['network_firewall_admin'])
        Vue.prototype.$auth = (res.menuCodeList || []).reduce((sum, key) => {
          return {
            ...sum,
            [key]: true
          }
        }, {})
        commit('baseInfo', res);
        updateRoute(routes)
        const defaultPath = router.getRoutes().filter(route => !route.meta.onlyMenu && !route.meta.isDefalut)[0]?.path
        if (defaultPath) {
          router.addRoute({
            path: '*',
            redirect: {
              path: defaultPath
            }
          })
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

const mutations = {
  baseInfo(state, update) {
    state.baseInfo = { ...update }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
